import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 控制搜索建议和搜索历史
    // 搜索历史记录
    kwList: [],
    // 搜索关键词数据
    searchList: [],
    value: ''
  }

  onLoad() {
    var kwList = wepy.getStorageSync('kw') || []
    this.kwList = kwList
  }

  computed = {
    isShowHistory() {
      if (this.value.length <= 0) return true
      return false;
    }
  }

  methods = {
    // 清空历史记录
    clearhistory() {
      this.kwList = []
      wepy.setStorageSync('kw', [])
    },
    // 去商品列表页
    goGoodsLIst(search) {
      wepy.navigateTo({
        url: '/pages/goods_list?query=' + search
      })
    },
    // 去商品详情页
    goGoodsDetail(id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + id
      })
    },
    /* 搜索框 */
    onChange(e) {
      this.value=e.detail.trim();
      if (e.detail.trim().length == 0) return this.searchList = []
      var search = e.detail
      this.getSearch(search)
    },

    onSearch(e) {
      var kw = e.detail.trim()
      if (kw.length <= 0) return;
      if (this.kwList.indexOf(kw) === -1) this.kwList.unshift(kw)
      this.kwList = this.kwList.slice(0, 10)
      wepy.setStorageSync('kw', this.kwList)
      // 搜索后跳转到详情页
      wepy.navigateTo({
        url: '/pages/goods_list?query=' + kw
      })
    },
    onCancel() {
      this.searchList = []
    }
  }
  // 获取搜索数据
  async getSearch(query) {
    const { data: res } = await wepy.get('/goods/search', { query })
    if (res.meta.status != 200)
      return wepy.baseToast();
    this.searchList = res.message.goods
    this.$apply()
  }
}